#!/bin/bash

option_o=0;
option_S=0;
option_c=0;

count=` cat ~/count-modified `;

count_total=` cat ~/count-total `;
count_total=` expr $count_total + 1 `;
echo $count_total>~/count-total;

limit=0;

limit_end=2000;
#1480 at most

ext_s=0;
ext_o=0;
last_is_o=0;

#the name after -o
obj="";
#input file name
input="";

for curOption in $@
do
	if [ $last_is_o == 1 ]; then
		obj=$curOption;
	else
		firstCh=${curOption:0:1};
		if [ "$firstCh" != "-" ]; then
			input=$curOption;
		fi
	fi
	if [ $curOption == "-o" ]; then
		option_o=1;
		last_is_o=1;
	else
		last_is_o=0;
	fi
	if [ $curOption == "-S" ]; then
		option_S=1;
	fi
	if [ $curOption == "-c" ] || [ $curOption == "-xc" ]; then
		option_c=1;
	fi
done

input_ext=${input##*.};

cmd1="";
cmd2="";
last_is_o=0;

need_step1=1;
if [[ $input_ext = "S" ]] || [[ $input_ext = "s" ]]; then
	need_step1=0;
fi

inrange=` query $@ `;
#if [[ $count -lt $limit ]];then
#	echo $count'<'$limit>>~/tmpcount;
#	inrange=0;
#fi;

#if [[ $count -gt $limit_end ]];then
#	echo $count'>'$limit_end>>~/tmpcount;
#	inrange=0;
#fi;

if [ $inrange == -1 ] || [ $inrange == 1 ] || [ $option_S == 1 ] || [ $option_c == 0 ] || [ $option_o == 0 ] || [ $input == "" ]; then
	echo $count_total>>~/cmd-unmodified;
	echo $@>>~/cmd-unmodified;
	gcc $@;
else
	echo ` expr $count + 1 `>~/count-modified;
	echo $count_total>>~/cmd-modified;
	echo $@>>~/cmd-modified;
#step 1: generate original asm file
	for curOption in $@
	do
		if [ $last_is_o == 1 ]; then
			curOption=$curOption".origin.s"
		fi
		if [ $curOption == "-o" ]; then
			last_is_o=1;
		else
			last_is_o=0;
		fi
		cmd1=$cmd1" "$curOption;
	done
	cmd1="-S "$cmd1;
	if [ $need_step1 == 1 ];then
	#	echo $cmd1>>~/tmpcmd;
		gcc $cmd1;
	fi
	
#step 2: modify the asm file to support replication
	origin_asm_file="";
	modified_asm_file="";
	if [ $need_step1 == 1 ];then
		modified_asm_file=$obj".modified.s";
		origin_asm_file=$obj".origin.s";
	else
		cp $input $input".backup";
		modified_asm_file=$input".modified.s";
		origin_asm_file=$input".backup";
	fi
#	cp $origin_asm_file $modified_asm_file;
#	/bin/ly_0.out <$origin_asm_file>$modified_asm_file;
	/bin/ly.out <$origin_asm_file>$modified_asm_file;
	
#exec gcc * obj.s -o obj
	if [ $need_step1 == 0 ]; then
		rm -f $input;
		cp $modified_asm_file $input;
	fi
	for curOption in $@
	do
		if [ $curOption == $input ] && [ $need_step1 == 1 ]; then
			curOption=$modified_asm_file;
		fi
		cmd2=$cmd2$curOption" ";
	done
#	echo $cmd2>>~/tmpcmd;
	gcc $cmd2;
	if [ $need_step1 == 0 ];then
		rm -f $input;
		cp $input".backup" $input;
	fi
fi
